﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using db;

namespace DMSMT
{
    public partial class MadeOrderFrm : Form
    {
        public MadeOrderFrm()
        {
            InitializeComponent();
        }

        private void search(string ordercode)
        {
            Log.LogText("开始查询中间库.....");
            string sql = "SELECT a.dealer_code, a.billcode, a.quoteid, a.dqzt, a.is_read  FROM TI_PT_PART_ORDER a  WHERE a.BILLCODE like '%" + ordercode + "%'";
            List<Hashtable> list = db.Dao.search("zj", sql);
            if (list == null || list.Count == 0)
            {
                Log.LogText(ordercode + "未传到中间库，查询中心库...");
                sql = "SELECT 1  FROM TT_PT_PART_ORDER   WHERE PURCHASE_ORDER_CODE ='" + ordercode + "'";
                Object obj = db.Dao.selectObject("dc", sql);
                if (obj == null)
                {
                    Log.LogText(ordercode + "订单号不存在检查订单号或店端到中心ogg接口.....");
                }
                else
                {
                    Log.LogText(ordercode + "订单号中心到中间ogg接口.....");
                }
                return;
            }
            if (list.Count > 1)
            {
                Log.LogText(ordercode + "订单号重复,到店端处理重复单号.....");
                return;
            }
            Hashtable ht = list[0];
            if (ht["dqzt"].Equals("130"))
            {
                Log.LogText(ordercode + "单据状态未同步到中间库!.....");
                return;
            }

            if (ht["is_read"].Equals("0"))
            {
                Log.LogText(ordercode + "订单上传存储过程未执行!.....");
                return;
            }
            Log.LogText(ordercode + "已传到中间库,到一体化系统查询订单信息.....");

            string tableName = ht["dealer_code"].ToString() + "T_QUOTE@SQLWLL";
            sql = "select * from " + tableName + " where billcode = '" + ordercode + "'";
            Hashtable htpv = db.Dao.select("zj", sql);
            if (htpv == null || htpv.Count == 0)
            {
                Log.LogText(ordercode + "上传订单存储过程已执行，订单未传到一体化，可能为存储过程执行失败!.....");
                return;
            }
            else
            {
                Log.LogText(ordercode + "已上传到一体化!");
                StringBuilder sb = new StringBuilder();
                sb.Append("--------------------------------------");
                sb.Append("\r\n");
                sb.Append("订单号:" + htpv["billcode"]);
                sb.Append("\r\n");
                sb.Append("销售单号:" + htpv["scbillcode"]);
                sb.Append("\r\n");
                sb.Append("订单状态:" + htpv["billstate"]);
                sb.Append("\r\n");
                sb.Append("当前状态:" + htpv["dqzt"]);
                sb.Append("\r\n");
                sb.Append("订单类型:" + htpv["ordertype"]);
                sb.Append("\r\n");
                sb.Append("--------------------------------------");
                Log.LogText(sb.ToString());
            }
        }

        private void btsearch_Click(object sender, EventArgs e)
        {
            string ordercode = tbbillcode.Text.Trim();
            if (string.IsNullOrEmpty(ordercode))
            {
                Log.LogError("订单号不能为空,输入完整订单号!");
                return;
            }
            try
            {
                search(ordercode);
            }
            catch (Exception ex)
            {
                Log.LogError("程序异常:" + ex.Message);
            }
        }

        private void btClearLog_Click(object sender, EventArgs e)
        {
        }

        private void MadeOrderFrm_Load(object sender, EventArgs e)
        {
            gb1.Visible = true;
        }

        private void btMCSearch_Click(object sender, EventArgs e)
        {
            string mc = tbMC.Text.Trim().ToUpper();
            //string netcode = tbNet_Code.Text.Trim();
            string ordercode = tbbillcode.Text.Trim();
            string msg = "";
            if (string.IsNullOrEmpty(mc))
            {
                msg += "图号号不能为空,输入物料图号!\r\n";
            }
            if (string.IsNullOrEmpty(ordercode))
            {
                msg += "订单号不能为空,输入订单号!";
            }
            if (!string.IsNullOrEmpty(msg))
            {
                Log.LogError(msg);
                return;
            }
            try
            {
                SearchStock(mc, ordercode);
            }
            catch (Exception ex)
            {
                Log.LogError("程序异常:" + ex.Message);
            }
        }

        private void SearchStock(string mc, string ordercode)
        {
            String sql = "select substr(pm.material_id,5) mid from tm_part_material_info pm where pm.material_code='" + mc + "'";
            int mid = Dao.selectInt("zj", sql);
            if (mid == 0)
            {
                throw new Exception("图号:" + mc + "不存在,检查图号!");
            }
            sql = "select tp.dealer_code from ti_pt_part_order tp where dealer_code is not null and  tp.billcode like '%" + ordercode + "%'";
            string ac = Dao.selectStr("zj", sql);
            Log.LogText("图号:" + mc + "\t物料ID:" + mid + "\tAgents_Code:" + ac);
            Log.LogText("查询中间库物料代理商库存...");
            sql = "select ps.stock_count,ps.agents_code from TI_PA_AGENTS_STOCK ps where m_id = " + mid;
            List<Hashtable> list = Dao.search("zj", sql);
            double sc = 0;
            Log.LogText("--------------------------------------");
            for (int i = 0; i < list.Count; i++)
            {
                Hashtable ht = list[i];
                string agents_code = ht["agents_code"].ToString();
                string stock_count = ht["stock_count"].ToString();
                string msg = agents_code + "\t库存:" + stock_count;
                if (agents_code.Equals(ac))
                {
                    msg += "\t\t ---物料所在代理商库存";
                    sc = double.Parse(stock_count);
                }
                Log.LogText(msg);
            }
            Log.LogText("--------------------------------------");
            if (sc > 0)
                return;
            Log.LogText("到一体化系统查询物料代理商库存...");
            string table = ac + "T_MATERIAL_STOCK@Sqlwll";
            sql = "SELECT SUM(ACTUALKC) AS stock_count FROM "
                + table + " WHERE UPDATETAG <> 3 and MID = " + mid;
            string sc_yth = Dao.selectStr("zj", sql);
            Log.LogText("一体化库存数量:" + sc_yth);
            if (!string.IsNullOrEmpty(sc_yth) && Convert.ToInt32(sc_yth) > 0)
            {
                //Log.LogText("物料一体化库存未同步到中间库,到中间库执行存储过程:YDMS_ORG_DLSKC");
                Log.LogText("物料一体化库存未同步到中间库,使用一体化库存更新中间库库存...");
                sql = "UPDATE TI_PA_AGENTS_STOCK T1 SET T1.UPDATE_DATE = SYSDATE,T1.STOCK_COUNT = " + sc_yth +
                        " WHERE T1.M_ID = " + mid + " AND T1.AGENTS_CODE = '" + ac + "'";
                int res = Dao.update("zj", sql);
                if (res > 0)
                {
                    Log.LogText("中间库库存更新成功,重新查询库存数量!");
                }

                sql = "UPDATE T_PA_AGENTS_STOCK T1 SET T1.UPDATE_DATE = SYSDATE,T1.STOCK_COUNT = " + sc_yth +
                        " WHERE T1.M_ID = " + mid + " AND T1.AGENTS_CODE = '" + ac + "'";
                res = Dao.update("dc", sql);
                if (res > 0)
                {
                    Log.LogText("中心库库存更新成功,重新查询库存数量!");
                }
                
            }
        }

        private void btClSearch_Click(object sender, EventArgs e)
        {
            string wdcode = tbNet_Code.Text.Trim();
            if (string.IsNullOrEmpty(wdcode))
            {
                MessageBox.Show("网点代码不能为空!");
                return;
            }

            string sql = @"select nvl(date" + DateTime.Today.Day +
                    ",0) ca  from pa_part_purchase_calender where net_code = " + wdcode +
                    "   and indent_year=" + DateTime.Today.Year
                    + " and indent_month=" + DateTime.Today.Month;
            int ca = Dao.selectInt("zj", sql);
            if (ca == 1)
                Log.LogText("订单日历已同步到中间库!");
            else
            {
                Log.LogText("订单日历未同步到中间库,查询一体化日历数据!");
                string format = @"SELECT M.CID, M.RLDATA, M.RLXQ
                              FROM (SELECT B.ORG_ID AS CID,
                                           A.RLDATA AS RLDATA,
                                           DECODE(DECODE(REPLACE(A.RLXQ, ',', CHR(39) || ',' || CHR(39)),
                                                         '''''',
                                                         '',
                                                         REPLACE(A.RLXQ, ',', CHR(39) || ',' || CHR(39))),
                                                  '请选择',
                                                  '',
                                                  '所有',
                                                  '星期一,星期二,星期三,星期四,星期五,星期六,星期日',
                                                  DECODE(REPLACE(A.RLXQ, ',', CHR(39) || ',' || CHR(39)),
                                                         '''''',
                                                         '',
                                                         REPLACE(A.RLXQ, ',', CHR(39) || ',' || CHR(39)))) AS RLXQ
                                      FROM V_PVZXK_BASIC_COMPANY A
                                      LEFT JOIN T_SYS_ORGANIZATION@Dmsct B
                                        ON A.CID = B.PA_ORG_CODE
                                       AND A.DLSCODE = B.AGENTS_CODE
                                     WHERE (RLXQ IS NOT NULL AND RLDATA IS NULL)
                                        OR RLXQ LIKE '%{0}%'
                                        OR TO_CHAR(A.CREATEDATE, 'YYYY-MM') LIKE '%{1}%'
                                        OR (RLXQ IS NOT NULL AND RLDATA IS NOT NULL)) M
                             WHERE M.CID = {2}";
                string y_m=DateTime.Today.ToString("yyyy-MM");
                sql = string.Format(format, y_m, y_m,wdcode);
                Hashtable ht = Dao.select("zj", sql);
                if (ht == null || ht.Count == 0)
                {
                    Log.LogText("一体化系统网点代码" + wdcode + "订单日历数据!");
                    return;
                }
                if (ht["rlxq"] != null)
                {
                    string week = ht["rlxq"].ToString();
                    Log.LogText("订单下发星期:" + week);
                    string today=DateTime.Today.ToString("dddd", new System.Globalization.CultureInfo("zh-cn"));
                    Log.LogText("今天:"+today);
                    if (week.Trim().Equals(today))
                    {
                        Log.LogText("今天是订单日历下发日期!");
                        return;
                    }
                }

                bool is_date=false;
                if (ht["rldata"] != null)
                {
                    string rldata = ht["rldata"].ToString();
                    string[] arr = rldata.Split(',');
                    string cls="";
                    foreach (string str in arr)
                    {
                        if (str.StartsWith(DateTime.Today.ToString("yyyy-MM")))
                        {
                            cls += str;
                            if (str.Equals(DateTime.Today.ToString("yyyy-MM-dd")))
                                is_date = true;
                        }
                    }
                    Log.LogText("本月订单日历下发日期:");
                    Log.LogText(cls);
                }
                if (is_date)
                    Log.LogText("今天是订单日历下发日期!");
                else
                    Log.LogText("今天不是订单日历下发日期!");
            }
        }

    }
}
